//
//  SCaptchaView.m
//  easyTest
//
//  Created by Samuel on 15/7/21.
//  Copyright (c) 2015年 banggo. All rights reserved.
//

#import "SCaptchaView.h"

@implementation SCaptchaView
{
    UIView *mainView;
    
    UIView *shadowView;
    
    NSMutableArray *btnArray;
    
    int transformCount;
    
    int tapCount;
}


- (id)initWithSCaptchaStyle:(SCaptcha)style;
{
    SCaptchaView *scv = [[SCaptchaView alloc]init];
    scv.style = style;
    return scv;
}
- (id)init
{
    return [self initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, [[UIScreen mainScreen]bounds].size.height)];
}

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {
        self.backgroundColor = [UIColor clearColor];
        shadowView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, [[UIScreen mainScreen]bounds].size.width, [[UIScreen mainScreen]bounds].size.height)];
        [shadowView setBackgroundColor:[UIColor blackColor]];
        [shadowView setAlpha:0];
        UITapGestureRecognizer *tapClose = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(closeSelfs:)];
        [shadowView addGestureRecognizer:tapClose];
        [self addSubview:shadowView];
        tapCount = 0;
    }
    return self;
}
- (void)closeSelfs:(UITapGestureRecognizer*)sender
{
    [self dismissWithAnimation];
}
- (void)showImmediately;
{
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    [self addSubview:mainView];
    [shadowView setAlpha:.3];
    [window addSubview:self];
}
- (void)showWithAnimation;
{
    UIWindow* window = [UIApplication sharedApplication].keyWindow;
    [window addSubview:self];
    [UIView animateWithDuration:.1 animations:^{
        shadowView.alpha = .3;
    } completion:^(BOOL finished) {
        [mainView setAlpha:0];
        [self addSubview:mainView];
        [UIView animateWithDuration:.2 animations:^{
            mainView.alpha = 1;
        }];
    }];
}

- (void)dismissImmediately;
{
    [self removeFromSuperview];
}
- (void)dismissWithAnimation;
{
    [UIView animateWithDuration:.1 animations:^{
        mainView.alpha = 0;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:.1 animations:^{
            shadowView.alpha = 0;
        } completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    }];
}

- (void)setDelegate:(NSObject<SCaptchaViewDelegate> *)delegate
{
    _delegate = delegate;
    
    mainView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 280, 180)];
    [mainView setCenter:CGPointMake([[UIScreen mainScreen]bounds].size.width/2, [[UIScreen mainScreen]bounds].size.height/2)];
    [mainView setBackgroundColor:[UIColor whiteColor]];
    mainView.layer.cornerRadius = 8;
    
    [self creatLabelTitle];
    [self creatImagePick];
    [self creatConfireButton];
    

    
    
    
}
- (void)creatLabelTitle
{
    UILabel *labels = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, 250, 50)];
    labels.text = @"点击下方图片旋转至正确位置，完成验证";
    [labels setFont:[UIFont boldSystemFontOfSize:15]];
    labels.textColor = [UIColor blackColor];
    labels.textAlignment = NSTextAlignmentCenter;
    labels.numberOfLines = 0;
    [mainView addSubview:labels];
}
- (void)creatImagePick
{
    /**
     *  获取随机图片
     */
    NSMutableArray *image4Jpg = [NSMutableArray array];
    while (1) {
        int imageNameCount = arc4random() % 20;
        if ([image4Jpg count]<1) {
            [image4Jpg addObject:[NSString stringWithFormat:@"%d.jpg",imageNameCount]];
        }
        for (NSString *getCount in image4Jpg) {
            if ([getCount intValue]!=imageNameCount && [image4Jpg count]<4) {
                [image4Jpg addObject:[NSString stringWithFormat:@"%d.jpg",imageNameCount]];
                break;
            }
        }
        if ([image4Jpg count]>=4) {
            break;
        }
    }
    NSLog(@"%@",image4Jpg);
    /**
     *  生成按钮
     */
    btnArray = [NSMutableArray array];
    for (int i = 0; i < [image4Jpg count];i++) {
        NSString *getName = [image4Jpg objectAtIndex:i];
        UIImage *getsImage = [UIImage imageNamed:getName];
        UIButton *btnc = [UIButton buttonWithType:UIButtonTypeCustom];
        [btnc setBackgroundImage:getsImage forState:UIControlStateNormal];
        [btnc setFrame:CGRectMake(15*(i+1)+i*50, 75, 50, 50)];
        [mainView addSubview:btnc];
        btnc.alpha = 1;
        btnc.tag = i;
        [btnArray addObject:btnc];
    }
    int btnCount = arc4random() % 4;
    for (UIButton *btnget in btnArray) {
        if (btnCount == btnget.tag) {
            transformCount = (arc4random() % 3)+1;
            btnget.transform = CGAffineTransformMakeRotation(M_PI_2*transformCount);
            [btnget addTarget:self action:@selector(rotate:) forControlEvents:UIControlEventTouchDown];
        }
    }
}



- (void)rotate:(UIButton*)sender {
    tapCount++;
    if (tapCount+transformCount>=5) {
//        return;
    }
    [UIView animateWithDuration:0.5 animations:^{
        sender.transform = CGAffineTransformMakeRotation(M_PI_2*(tapCount+transformCount));
    } completion:^(BOOL finished) {
        if([self.delegate respondsToSelector:@selector(sCaptchaView:didSelectRowAtIndex:isRight:)])
        {
            BOOL isRight = ((tapCount+transformCount)%4==0)?YES:NO;
            [self.delegate sCaptchaView:self didSelectRowAtIndex:sender.tag isRight:isRight];
        }
    }];

    
}



- (void)creatConfireButton
{
    UIButton *buttons = [UIButton buttonWithType:UIButtonTypeCustom];
    [buttons setFrame: CGRectMake(40, 140, 200, 30)];
    [buttons setTitle:@"确定" forState:UIControlStateNormal];
    [buttons.titleLabel setFont:[UIFont systemFontOfSize:14]];
    [buttons setBackgroundColor:[UIColor blackColor]];
    [buttons setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [buttons addTarget: self action:@selector(bottnActions:) forControlEvents:UIControlEventTouchDown];
    buttons.layer.cornerRadius = 4;

    [mainView addSubview:buttons];
}
- (void)bottnActions:(UIButton*)sender
{
    BOOL isRight = ((tapCount+transformCount)%4==0)?YES:NO;
    if([self.delegate respondsToSelector:@selector(sCaptchaViewDidButton:isRight:)])
    {
        [self.delegate sCaptchaViewDidButton:sender isRight:isRight];
    }
    if(!isRight && self.isOpenShake)
    {
        [self shakeView:mainView];
    }
}

-(void)shakeView:(UIView*)viewToShake
{
    CGFloat t =2.0;
    CGAffineTransform translateRight  =CGAffineTransformTranslate(CGAffineTransformIdentity, t,0.0);
    CGAffineTransform translateLeft =CGAffineTransformTranslate(CGAffineTransformIdentity,-t,0.0);
    
    viewToShake.transform = translateLeft;
    
    [UIView animateWithDuration:0.07 delay:0.0 options:UIViewAnimationOptionAutoreverse|UIViewAnimationOptionRepeat animations:^{
        [UIView setAnimationRepeatCount:2.0];
        viewToShake.transform = translateRight;
    } completion:^(BOOL finished){
        if(finished){
            [UIView animateWithDuration:0.05 delay:0.0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                viewToShake.transform =CGAffineTransformIdentity;
            } completion:NULL];
        }
    }];
}

















@end
